package com.andy.blog.dal.service.impl;

import com.andy.blog.common.exception.BlogServiceException;
import com.andy.blog.common.utils.SecurityUtils;
import com.andy.blog.common.utils.TransformUtils;
import com.andy.blog.dal.domain.CategoryDO;
import com.andy.blog.dal.mapper.CategoryMapper;
import com.andy.blog.dal.service.CategoryDalService;
import com.andy.blog.dal.vo.CategoryVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by andy on 2023/6/21 12:47
 */
@Service
public class CategoryDalServiceImpl implements CategoryDalService {

    @Resource
    private CategoryMapper categoryMapper;

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<CategoryDO> buildQueryWrapper(CategoryVO categoryVO) {
        return new LambdaQueryWrapper<CategoryDO>()
                .like(StringUtils.isNotBlank(categoryVO.getCategoryName()), CategoryDO::getCategoryName, categoryVO.getCategoryName());
    }

    @Override
    public IPage<CategoryDO> selectListByPage(CategoryVO categoryVO) {
        LambdaQueryWrapper<CategoryDO> lambdaQueryWrapper = buildQueryWrapper(categoryVO);
        IPage<CategoryDO> page = new Page<>(categoryVO.getPageNum(), categoryVO.getPageSize());
        return categoryMapper.selectPage(page, lambdaQueryWrapper);
    }

    @Override
    public void addCategory(CategoryVO categoryVO) {
        CategoryDO categoryDO = TransformUtils.transform(categoryVO, CategoryDO.class);
        if (null == categoryDO) {
            throw new BlogServiceException("入参不能为空");
        }
        categoryDO.setCreateBy(SecurityUtils.getUsername());

        categoryMapper.insert(categoryDO);
    }

    @Override
    public CategoryDO getById(Long id) {
        return categoryMapper.selectById(id);
    }

    @Override
    public void updateById(CategoryVO categoryVO) {
        CategoryDO categoryDO = TransformUtils.transform(categoryVO, CategoryDO.class);
        if (null == categoryDO) {
            throw new BlogServiceException("入参不能为空");
        }
        categoryDO.setUpdateBy(SecurityUtils.getUsername());

        categoryMapper.updateById(categoryDO);
    }

    @Override
    public List<CategoryDO> selectList(CategoryVO categoryVO) {
        LambdaQueryWrapper<CategoryDO> lambdaQueryWrapper = buildQueryWrapper(categoryVO);
        return categoryMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public Long selectCategoryCount(CategoryVO categoryVO) {
        LambdaQueryWrapper<CategoryDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        return categoryMapper.selectCount(lambdaQueryWrapper);
    }
}
